package com.lsm.sm.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.lsm.sm.service.VerifyCode;
import com.lsm.sm.util.Const;
import com.lsm.sm.util.WebUtil;
import com.opensymphony.xwork2.ActionSupport;

/**
 * Create Date:2013-09-23
 * @author Liushimao
 */
@Controller("verifyCodeAction")
@Scope("prototype")
public class VerifyCodeAction extends ActionSupport{
	private static final long serialVersionUID = 1874595792576873395L;
	@Resource
	private VerifyCode verifyCode;
	private String error;
	private String vc;
	private InputStream stream;
	
	
	public String execute(){
		try{
			setStream(verifyCode.getCode());
			String vc = (String)verifyCode.getAnswer();
			WebUtil.addInSession( Const.VC, vc );
		}catch( Exception e ){
			setStream( new ByteArrayInputStream( "错误".getBytes() ) );
		}
		return SUCCESS;
	}
	
	public String checkVc(){
		try{
			//会话是否过期如果过期，则新建 一个 session。
			Map<String, Object> session = WebUtil.getSession();
			Integer itg = (Integer)session.get( Const.NEW_SESSION );
			
			if( itg!=null && itg.intValue() == 1 ){
				setError( "会话已过期" );
			}else{
				String tempVc = (String) session.get( Const.VC );
				if( tempVc == null ){
					setError( "请获取新的验证码！");
				}else if( tempVc!=null && tempVc.equalsIgnoreCase(vc) ){
					setError( "验证码正确！&true" );
				}else{
					setError( "验证码错误！");
				}
			}
			stream = new ByteArrayInputStream( getError().getBytes( "utf8" ) );
		}catch (UnsupportedEncodingException e){
			e.printStackTrace();
			return "verifyCode";
		}
		return "verifyCode";
	}
	
	public InputStream getStream() {
		return stream;
	}

	public void setStream(InputStream stream) {
		this.stream = stream;
	}
	
	public String getError() {
		return error;
	}
	
	public void setError(String error) {
		this.error = error;
	}

	public String getVc() {
		return vc;
	}

	public void setVc(String vc) {
		this.vc = vc;
	}

	public void  setVerifyCode( VerifyCode verifyCode ){
		this.verifyCode = verifyCode;
	}
}
